<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <!-- 主要内容区 -->
    <div class="p-6 bg-gray-100 flex-1">
        <!-- 搜索区域 -->
        <div class="bg-white p-6 rounded-lg mb-6">
            <div class="grid grid-cols-5 gap-6">
                <el-input v-model="searchForm.keyword" placeholder="请输入题目名称" class="w-64 max-h-32" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
                <el-select v-model="searchForm.type" placeholder="题目类型" class="w-full !rounded-button">
                    <el-option label="单选题" value="single" />
                    <el-option label="多选题" value="multiple" />
                    <el-option label="判断题" value="judge" />
                </el-select>
                <el-select v-model="searchForm.major" placeholder="专业类型" class="w-full !rounded-button">
                    <el-option label="计算机科学" value="computer_science" />
                    <el-option label="软件工程" value="software_engineering" />
                    <el-option label="数据科学" value="data_science" />
                    <el-option label="信息安全" value="information_security" />
                    <el-option label="人工智能" value="artificial_intelligence" />
                    <el-option label="非专业" value="non_major" />
                </el-select>
                <el-select v-model="searchForm.difficulty" placeholder="难度等级" class="w-full !rounded-button">
                    <el-option label="简单" value="easy" />
                    <el-option label="中等" value="medium" />
                    <el-option label="困难" value="hard" />
                </el-select>
                <div class="flex justify-end  space-x-4">
                    <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="handleSearch">
                        <el-icon class="mr-1">
                            <Search />
                        </el-icon>搜索
                    </el-button>
                    <el-button class="!rounded-button whitespace-nowrap" @click="resetSearch">
                        <el-icon class="mr-1">
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </div>
            </div>
            <!-- 表格区域 -->
            <div class="bg-white p-6 rounded-lg">
                <div class="flex justify-between mb-4">
                    <div class="space-x-4">
                        <el-button type="primary" class="!rounded-button" @click="openDialog('add')">
                            <el-icon class="mr-1">
                                <Plus />
                            </el-icon>新增
                        </el-button>
                        <el-button type="success" class="!rounded-button" @click="handleImport">
                            <el-icon class="mr-1">
                                <Upload />
                            </el-icon>导入
                        </el-button>
                        <el-button type="warning" class="!rounded-button" @click="handleExport">
                            <el-icon class="mr-1">
                                <Download />
                            </el-icon>导出
                        </el-button>
                    </div>

                </div>
                <el-table :data="tableData" style="width: 100%">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="题目编号" prop="id" width="100" />
                    <el-table-column label="所属题库" prop="title" min-width="100" />
                    <el-table-column label="题目内容" prop="questionContent" min-width="300" />
                    <el-table-column label="题目类型" prop="type" width="120">
                        <template #default="{ row }">
                            <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="createTime" width="180" :formatter="formatDate"/>
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="scope">
                            <div class="flex space-x-2">
                                <el-button size="small" @click="openDialog('edit', scope.row)"
                                    class="!rounded-button whitespace-nowrap w-16">编辑</el-button>
                                <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                                    class="!rounded-button whitespace-nowrap w-16">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="flex justify-between items-center mt-4">
                    <span class="text-gray-500">共 {{ total }} 条</span>
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 30, 50]" :total="total" layout="sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
    </div>
    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增用户' : '编辑用户'" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="题目名称" prop="questionName">
                <el-input type="textarea" v-model="form.questionName" placeholder="请输入题目名称"
                    :autosize="{ minRows: 2, maxRows: 6 }" />
            </el-form-item>
            <el-form-item label="题目类型" prop="questionType">
                <el-input v-model="form.questionType" placeholder="请输入题目类型" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit(formRef)">确认</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 上传文件弹窗 -->
    <el-upload ref="upload" :action="uploadUrl" :before-upload="beforeUpload" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" accept=".xls,.xlsx" show-file-list="false" :auto-upload="false">
    </el-upload>
</template>
<script lang="ts" setup>
import { ref,onMounted } from 'vue';
import * as XLSX from "xlsx";  // 引入 xlsx 库
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";
import {getAssessmentQuestionList} from "../../api/admin/topic.js"
import {
    HomeFilled,
    Setting,
    Search,
    Plus,
    Upload,
    Download,
    Bell,
    Refresh,
    Grid,
    List
} from '@element-plus/icons-vue';
onMounted(()=>{
    getList(null)
})

// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};
async function getList(data) {
    await getAssessmentQuestionList(data).then(function (response) {
        tableData.value=response.rows
    })
}
const activeMenu = ref('2-1');
const userAvatar = 'https://ai-public.mastergo.com/ai/img_res/43027ddc550ee02072d5aba79aaf0566.jpg';
const searchForm = ref({
    keyword: '',
    type: '',
    difficulty: '',
    major: '',
    dateRange: []
});
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const tableData = ref([]);
const getTypeTagType = (type: string) => {
    const typeMap: Record<string, string> = {
        '1': '',//单选题
        '2': 'success',//多选题
        '3': 'warning'//判断题
    };
    return typeMap[type] || 'info';
};
const handleSearch = () => {
    console.log('搜索', searchForm.value);
};
const resetSearch = () => {
    searchForm.value = {
        keyword: '',
        type: '',
        difficulty: '',
        dateRange: []
    };
};
//分页相关
const handleSizeChange = (val: number) => {
    pageSize.value = val;
};
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref('');
const formRef = ref<FormInstance>();
//弹框表单
const form = ref({
    questionName: '',       // 题目名称
    questionType: '',    // 题目描述
});

const openDialog = (type: string, row?: any) => {
    dialogType.value = type;
    dialogVisible.value = true;

    if (type === 'edit' && row) {
        // 将传入的 `row` 数据正确映射到表单字段
        form.value.questionName = row.title || ''; // 题目名称
        form.value.questionType = row.type || '';  // 题目类型
    } else {
        // 重置表单
        form.value = {
            questionName: '',
            questionType: '',
        };
    }
};



//提交
const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (valid) {
            console.log('提交表单', form);
            dialogVisible.value = false;
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功');
        }
    });
};

//删除用户
const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除该用户吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        console.log('删除用户', row);
        ElMessage.success('删除成功');
    }).catch(() => { });
};

// 导入功能
const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx, .xls';
    input.onchange = (e: any) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event: any) => {
                const data = event.target.result;
                const wb = XLSX.read(data, { type: 'array' });
                const ws = wb.Sheets[wb.SheetNames[0]];
                const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
                console.log('导入数据:', json);
                // 假设你将数据存入 tableData
                tableData.value = json.slice(1).map((row: any) => {
                    return {
                        id: row[0],
                        username: row[1],
                        nickname: row[2],
                        phone: row[3],
                        account: row[4],
                        address: row[5],
                        status: row[6] === '启用', // 状态转换
                        createTime: row[7]
                    };
                });
                ElMessage.success('文件导入成功');
            };
            reader.readAsArrayBuffer(file);
        }
    };
    input.click();
};

// 导出功能
const handleExport = () => {
    const ws = XLSX.utils.json_to_sheet(tableData.value);  // 将 tableData 转为 sheet
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(data);
    const link = document.createElement('a');
    link.href = url;
    link.download = '用户数据.xlsx';  // 设置下载的文件名
    link.click();
    ElMessage.success('文件导出成功');
};
</script>
<style scoped>
.el-menu {
    border-right: none !important;
}

:deep(.el-menu-item) {
    color: #fff !important;
}

:deep(.el-sub-menu__title) {
    color: #fff !important;
}

:deep(.el-menu--inline) {
    background-color: rgba(0, 0, 0, 0.1) !important;
}

:deep(.el-input__wrapper),
:deep(.el-select),
:deep(.el-date-editor) {
    width: 100% !important;
}

:deep(.el-table) {
    --el-table-border-color: #ebeef5;
    --el-table-header-bg-color: #f5f7fa;
}
</style>
